<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="请输入MAC信息" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" clearable/>
      <!--      <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">-->
      <!--        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />-->
      <!--      </el-select>-->
      <el-select v-model="listQuery.type" placeholder="设备类型" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.areanum" placeholder="区域信息" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarAreanumOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.state" placeholder="设备状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarStateOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <!--      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">-->
      <!--        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />-->
      <!--      </el-select>-->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button>
      <el-button v-if="checkPermission(['admin'])" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"  @click="$router.push('/form/index')">
        新增
      </el-button>
      <!--      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">-->
      <!--        Export-->
      <!--      </el-button>-->
      <!--      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">-->
      <!--        reviewer-->
      <!--      </el-checkbox>-->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="设备物理编号" width="250px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.device_mac }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备名称" min-width="150px">
        <template slot-scope="{row}">
          <el-tag>{{ row.device_type | typeFilter }}</el-tag>
          <span class="link-type" @click="handleUpdate(row)">{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属区域" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.subject_area | areaFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="银行信息" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.device_attribute | bankFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工地信息" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.subject_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.device_state | statusFilter">
            {{ row.device_state | stateFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="checkPermission(['admin'])" label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <!--          <el-button v-if="row.status!='published'" size="mini" type="success" @click="handleModifyStatus(row,'published')">-->
          <!--            Publish-->
          <!--          </el-button>-->
          <!--          <el-button v-if="row.status!='draft'" size="mini" @click="handleModifyStatus(row,'draft')">-->
          <!--            Draft-->
          <!--          </el-button>-->
          <!--                <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">-->
          <!--                  删除-->
          <!--                </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 600px; margin-left:150px;">
        <el-form-item label="项目名称" prop="title">
          <el-input :value="temp.subject_name" />
        </el-form-item>
        <el-form-item label="项目编号" prop="num">
          <el-input :value="temp.num" />
        </el-form-item>
        <!--        <el-form-item label="更新时间" prop="timestamp">-->
        <!--          <el-date-picker v-model="temp.timestamp" type="datetime" placeholder="Please pick a date" />-->
        <!--        </el-form-item>-->
        <el-form-item label="合作银行" prop="bank">
          <el-input :value="temp.bank | bankFilter" />
        </el-form-item>
        <el-form-item label="项目状态" prop="state">
          <el-select v-model="temp.state " placeholder="请选择项目状态">
            <el-option label="停工" value="0" />
            <el-option label="已开工" value="1" />
            <el-option label="完工" value="2" />
            <el-option label="筹建" value="3" />
            <el-option label="立项" value="4" />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="Imp">-->
        <!--          <el-rate v-model="temp.importance" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" :max="3" style="margin-top:8px;" />-->
        <!--        </el-form-item>-->
        <el-form-item label="备注">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData('dataForm')">
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  // import { fetchPv, createArticle} from '@/api/article'
  import waves from '@/directive/waves' // waves directive
  import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  // import {  UpdateSubject, DelSubject } from '@/api/subject'
  import { GetListDevice } from '@/api/device'
  // import { scrollTo } from '@/utils/scroll-to'

  import checkPermission from '@/utils/permission' // 权限判断函数
  // 设备类型信息
  const calendarTypeOptions = [
    { key: '0', display_name: '注册机' },
    { key: '1', display_name: '考勤机' },
    { key: '2', display_name: '4G平板考勤机' },
    { key: '3', display_name: '测温平板' },
    { key: '4', display_name: '平板' },
    { key: '5', display_name: '海思平板' },
    { key: '6', display_name: '老版平板' },
    { key: '8', display_name: '路由器' },
    { key: '7', display_name: '数据卡' },
    { key: '9', display_name: '其他' }
  ]

  // 区域信息
  const calendarAreaOptions = [
    { key: '371601', display_name: '市直管' },
    { key: '371602', display_name: '滨城区' },
    { key: '371604', display_name: '开发区' },
    { key: '371605', display_name: '高新区' },
    { key: '371606', display_name: '北海新区' },
    { key: '371621', display_name: '惠民县' },
    { key: '371622', display_name: '阳信县' },
    { key: '371623', display_name: '无棣县' },
    { key: '371624', display_name: '沾化区' },
    { key: '371625', display_name: '博兴县' },
    { key: '371626', display_name: '邹平市' },
    { key: '371627', display_name: '工业园区' }
  ]
  // 区域信息
  const calendarAreanumOptions = [
    { key: '371601', display_name: '市直管' },
    { key: '371602', display_name: '滨城区' },
    { key: '371604', display_name: '开发区' },
    { key: '371605', display_name: '高新区' },
    { key: '371606', display_name: '北海新区' },
    { key: '371621', display_name: '惠民县' },
    { key: '371622', display_name: '阳信县' },
    { key: '371623', display_name: '无棣县' },
    { key: '371624', display_name: '沾化区' },
    { key: '371625', display_name: '博兴县' },
    { key: '371626', display_name: '邹平市' },
    { key: '371627', display_name: '工业园区' }
  ]
  // 状态信息
  const calendarStateOptions = [
    { key: '0', display_name: '未使用' },
    { key: '1', display_name: '可使用' },
    { key: '2', display_name: '使用中' },
    { key: '3', display_name: '维修中' }
  ]
  // 合作银行信息
  const calendarBankOptions = [
    { key: '0', display_name: '企业自购所有' },
    { key: '8', display_name: '库存中' },
    { key: '1', display_name: '农商银行' },
    { key: '2', display_name: '邮储银行' },
    { key: '3', display_name: '工商银行' },
    { key: '4', display_name: '中国银行' },
    { key: '5', display_name: '兴业银行' },
    { key: '6', display_name: '恒丰银行' },
    { key: '7', display_name: '东营银行' },
    { key: '9', display_name: '其他' }
  ]
  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})
  // 获取项目的状态信息
  const calendarStateKeyValue = calendarStateOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})
  // 获取合作银行的信息
  const calendarBankKeyValue = calendarBankOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  // 获取项目区域信息
  const calendarAreaKeyValue = calendarAreaOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})
  // 获取项目区域信息
  const calendarAreanumKeyValue = calendarAreanumOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'ComplexTable',
    components: { Pagination },
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          0: 'error',
          1: 'success',
          3: 'danger',
          2: 'warning'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      },
      stateFilter(type) {
        return calendarStateKeyValue[type]
      },
      bankFilter(type) {
        return calendarBankKeyValue[type]
      },
      areaFilter(type) {
        return calendarAreaKeyValue[type]
      },
      areanumFilter(type) {
        return calendarAreanumKeyValue[type]
      }
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          importance: undefined,
          title: undefined,
          type: undefined,
          sort: '+id'
        },
        importanceOptions: [1, 2, 3],
        calendarTypeOptions,
        calendarAreaOptions,
        calendarAreanumOptions,
        // sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        statusOptions: ['published', 'draft', 'deleted'],
        calendarStateOptions,
        showReviewer: false,
        temp: {
          id: undefined,
          device_mac: '',
          bank: '',
          timestamp: new Date(),
          title: '',
          type: '',
          device_state: '',
          device_type:''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '修改项目状态',
          create: 'Create'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          type: [{ required: true, message: 'type is required', trigger: 'change' }],
          timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
          title: [{ required: true, message: 'title is required', trigger: 'blur' }],
          bank: [{ required: true, message: 'title is required', trigger: 'blur' }],
          state: [{ required: true, message: '请选择项目状态', trigger: 'change' }]
        },
        downloadLoading: false
      }
    },
    created() {
      this.getList()
    },
    methods: {
      checkPermission,
      getList(val) {
        this.listLoading = true
        // eslint-disable-next-line eqeqeq
        if (val != undefined) {
          this.page = val.page,
            this.limit = val.limit
        }
        this.type = this.listQuery.type
        this.title = this.listQuery.title
        this.areanum = this.listQuery.areanum
        this.state = this.listQuery.state
        GetListDevice(
          {
            page: this.page,
            limit: this.limit,
            device_type: this.type,
            device_mac: this.title,
            device_state:this.state,
            subject_area:this.areanum
          }).then((res) => {
          // eslint-disable-next-line eqeqeq
          if (res.code == '20000') {
            this.list = res.data
            // console.log(this.list)
            this.total = res.msg
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)

            // this.$message('提交成功!')
          } else {
            this.$message({
              message: '提交失败，请联系管理员!',
              type: 'error'
            })
          }
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作Success',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          status: '',
          type: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
            this.temp.author = 'vue-element-admin'
            createArticle(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData(dataForm) {
        this.$refs['dataForm'].validate((valid) => {
          const tempData = Object.assign({}, this.temp)
          console.log(tempData)
          if (valid) {
            UpdateSubject(
              {
                subject_state: tempData.state,
                subject_num: tempData.num
              }).then((res) => {
              if (res.code == '20000') {
                // console.log(this.list)
                setTimeout(() => {
                  this.listLoading = false
                }, 1.5 * 1000)

                //  this.$message('修改成功!')
                if (res.data == 0) {
                  this.$notify({
                    title: '信息',
                    message: '数据相同，无需重复提交',
                    type: 'warning'
                  })
                } else {
                  this.$notify({
                    title: '信息',
                    message: '提交成功',
                    type: 'success'
                  })
                  this.dialogFormVisible = false
                }
              } else {
                this.$message({
                  message: '提交失败，请联系管理员!',
                  type: 'error'
                })
              }
            })
          }
        })
      },
      handleDelete(row, index) {
        console.log(row.num, index)
        DelSubject(
          {
            subject_num: row.num
          }).then((res) => {
          if (res.code == '20000') {
            // console.log(this.list)
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)

            //  this.$message('修改成功!')
            if (res.data == 0) {
              this.$notify({
                title: '信息',
                message: '已删除，无需重复操作',
                type: 'warning',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '信息',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            }
          } else {
            this.$message({
              message: '删除失败，请联系管理员史岩松!',
              type: 'error'
            })
          }
        })
        this.list.splice(index, 1)
      },
      handleFetchPv(pv) {
        fetchPv(pv).then(response => {
          this.pvData = response.data.pvData
          this.dialogPvVisible = true
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
</script>
